// ignore_for_file: unnecessary_this

import 'package:flutter/material.dart';
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;

class HttpDemo extends StatefulWidget {
  HttpDemo({Key? key}) : super(key: key);

  @override
  State<HttpDemo> createState() => _HttpDemoState();
}

class _HttpDemoState extends State<HttpDemo> {
  List list = [];
  @override
  void initState() {
    // 初始化数据
    Map map = {"name": '张三', "age": 12};
    String strData = convert.jsonEncode(map); // map 转为json字符串
    print(strData);
    print(convert.jsonDecode(strData)); // json字符串转为map
    // print(map is Map);
    // print(strData is String);
    _getData(); // 初始化数据
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('http请求数据'),
        ),
        body: ListView(
          children: <Widget>[
            ElevatedButton(
              onPressed: _getData,
              child: Text('get请求数据'),
            ),
            SizedBox(
              height: 20,
            ),
            ElevatedButton(
              onPressed: _postData,
              child: Text('post请求数据'),
            ),
            Column(
              children: this.list.isNotEmpty
                  ? this
                      .list
                      .map((e) => ListTile(title: Text(e['id'])))
                      .toList()
                  : [],
            )
          ],
        ));
  }

  void _getData() async {
    print('执行了');
    var url = Uri.https(
      'www.googleapis.com',
      '/books/v1/volumes',
      {'q': '{http}'}, // 传参
    );
    print(url);

    // Await the http get response, then decode the json-formatted response.
    var response = await http.get(url);
    if (response.statusCode == 200) {
      // 从响应体中获取数据
      var jsonResponse = convert.jsonDecode(response.body);
      var itemCount = jsonResponse['totalItems'];
      print(jsonResponse);
      setState(() {
        this.list = jsonResponse['items'];
      });
    } else {
      print('Request failed with status: ${response.statusCode}.');
    }
  }

  void _postData() async {
    print('执行了');
    var response = await http.post(Uri.https('example.com', 'whatsit/create'),
        body: {'name': 'doodle', 'color': 'blue'});
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');

    // 读取静态文件
    // print(await http.read(Uri.parse('https://example.com/foobar.txt')));
  }
}
